/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.snowy.hidden.biz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snowy.framework.common.base.dto.SaBaseLoginUser;
import com.snowy.framework.common.base.dto.SlicedQueryResult;
import com.snowy.framework.common.base.vo.LoginUser;
import com.snowy.framework.common.resp.BaseResp;
import com.snowy.framework.common.resp.BaseRespUtil;
import com.snowy.framework.exception.UABPException;
import com.snowy.framework.util.StpLoginUserUtil;
import com.snowy.hidden.biz.domain.model.HiddenReport;
import com.snowy.hidden.biz.domain.model.ReportAuditRecord;
import com.snowy.hidden.biz.domain.req.*;
import com.snowy.hidden.biz.domain.resp.HiddenReportResp;
import com.snowy.hidden.biz.domain.resp.ReportAuditRecordResp;
import com.snowy.hidden.biz.enums.*;
import com.snowy.hidden.biz.mapper.HiddenReportMapper;
import com.snowy.hidden.biz.mapper.ReportAuditRecordMapper;
import com.snowy.hidden.biz.mapper.TaskMapper;
import com.snowy.hidden.biz.service.DictService;
import com.snowy.hidden.biz.service.HiddenReportService;
import com.snowy.hidden.constant.AuthConstant;
import com.snowy.hidden.user.domain.model.AppletUser;
import com.snowy.hidden.user.domain.model.SysUser;
import com.snowy.hidden.user.domain.req.UserListByRoleListReq;
import com.snowy.hidden.user.mapper.AppletUserMapper;
import com.snowy.hidden.user.mapper.SysRoleMapper;
import com.snowy.hidden.user.mapper.SysUserMapper;
import com.snowy.hidden.user.service.SysRoleService;
import com.snowy.hidden.util.LngLonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 隐患上报信息Service接口实现类
 *
 * @author H
 * @date 2025/10/17 16:36
 **/
@Slf4j
@Service("hiddenReportService")
public  class HiddenReportServiceImpl extends ServiceImpl<HiddenReportMapper, HiddenReport> implements HiddenReportService {
    @Resource
    private AppletUserMapper appletUserMapper;
    @Resource
    private DictService dictService;
    @Resource
    private HiddenReportMapper hiddenReportMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private ReportAuditRecordMapper reportAuditRecordMapper;
    @Resource
    private TaskMapper taskMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public BaseResp add(HiddenReportAddParam hiddenReportAddParam, LoginUser userInfo) {
        log.info("==reportInfo===" + JSON.toJSONString(hiddenReportAddParam, true));
        HiddenReport hiddenReport = new HiddenReport();
        //坐标转换
        double[] doubles = LngLonUtil.gcj02_To_Bd09(hiddenReportAddParam.getLatitude(), hiddenReportAddParam.getLongitude());
        hiddenReport.setLatitude(LngLonUtil.retain6(doubles[0]));
        hiddenReport.setLongitude(LngLonUtil.retain6(doubles[1]));
        //上报人信息
        hiddenReport.setPlatformUserId(userInfo.getPlatformUserId());
        hiddenReport.setUserId(userInfo.getUserId());
        hiddenReport.setUserName(userInfo.getUserName());
        hiddenReport.setUserPhone(userInfo.getPhone());
        hiddenReport.setHiddenType(hiddenReportAddParam.getHiddenType());
        hiddenReport.setHiddenRemark(hiddenReportAddParam.getHiddenRemark());
        hiddenReport.setAddress(hiddenReportAddParam.getAddress());
        hiddenReport.setProvince(hiddenReportAddParam.getProvince());
        hiddenReport.setCity(hiddenReportAddParam.getCity());
        hiddenReport.setDistrict(hiddenReportAddParam.getDistrict());

        //解析图片数量
        String paths = CollUtil.join(hiddenReportAddParam.getFliePathImage(), ";");
        hiddenReport.setFliePath(paths);

        //音频
        hiddenReport.setSoundPath(hiddenReportAddParam.getSoundPath());

        hiddenReport.setCurrentStatus(ShowStatusEnum.WAIT_VERIFY.getValue());
        hiddenReport.setApproval(AuditStatusEnum.WAIT_ALLOCATE.getValue());

        this.save(hiddenReport);
        return BaseRespUtil.Success();
    }

    //过期

    @Override
    public BaseResp queryPage(HiddenReportPageReq hiddenReportPageReq) {
        //获取当前登录人
        LoginUser userInfo = AuthConstant.userLocal.get();

        Integer pageIndex = hiddenReportPageReq.getPageIndex();
        Integer pageSize = hiddenReportPageReq.getPageSize();

        //添加查询条件
        LambdaQueryWrapper<HiddenReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Page<HiddenReport> page = new Page<>(pageIndex, pageSize);
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(hiddenReportPageReq.getUserName()), HiddenReport::getUserName, hiddenReportPageReq.getUserName());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(hiddenReportPageReq.getUserPhone()), HiddenReport::getUserPhone, hiddenReportPageReq.getUserPhone());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(hiddenReportPageReq.getHiddenType()), HiddenReport::getHiddenType, hiddenReportPageReq.getHiddenType());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(hiddenReportPageReq.getHiddenLevel()), HiddenReport::getHiddenLevel, hiddenReportPageReq.getHiddenLevel());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(hiddenReportPageReq.getRectificationOrgId()), HiddenReport::getRectificationOrgId, hiddenReportPageReq.getRectificationOrgId());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(hiddenReportPageReq.getCurrentStatus()), HiddenReport::getCurrentStatus, hiddenReportPageReq.getCurrentStatus());
        lambdaQueryWrapper.in(ObjectUtil.isNotEmpty(hiddenReportPageReq.getApprovals()), HiddenReport::getApproval, hiddenReportPageReq.getApprovals());
        //包含查询待核实状态，添加核实人id
        if (ObjectUtil.isNotEmpty(hiddenReportPageReq.getApprovals())) {
            if (hiddenReportPageReq.getApprovals().contains(AuditStatusEnum.WAIT_VERIFY.getValue())) {
                lambdaQueryWrapper.eq(HiddenReport::getVerifyUserId, userInfo.getPlatformUserId());
            }
            if (hiddenReportPageReq.getApprovals().contains(AuditStatusEnum.BIZ_AUDIT.getValue())) {
                lambdaQueryWrapper.eq(HiddenReport::getRectificationUserId, userInfo.getPlatformUserId());
            }
        }


        lambdaQueryWrapper.orderByDesc(HiddenReport::getCreateTime);

        //分页查询
        IPage<HiddenReport> iPage = this.getBaseMapper().selectPage(page, lambdaQueryWrapper);
        //IPage<HiddenReportResp> hiddenReportRespIPage= iPage.convert(hiddenReport -> Convert.convert(HiddenReportResp.class, hiddenReport));
        IPage<HiddenReportResp> hiddenReportRespIPage = iPage.convert(hiddenReport -> {
            HiddenReportResp hiddenReportResp = Convert.convert(HiddenReportResp.class, hiddenReport);
            //类型转换
            hiddenReportResp.setHiddenTypeStr(dictService.getChildeLableByValue("hiddenType", hiddenReport.getHiddenType().toString()));
            return hiddenReportResp;

        });

        SlicedQueryResult<HiddenReportResp> slicedQueryResult = new SlicedQueryResult<>(pageIndex, pageSize, iPage.getTotal(), hiddenReportRespIPage.getRecords());
        return BaseRespUtil.Success(slicedQueryResult);
    }

    @Override
    public BaseResp allocateVerifyUser(HiddenReportAllocateReq hiddenReportAllocateReq) {
        HiddenReport hiddenReport = hiddenReportMapper.selectById(hiddenReportAllocateReq.getReportId());
        hiddenReport.setVerifyUserId(hiddenReportAllocateReq.getVerifyUserId());
        hiddenReport.setVerifyUserName(hiddenReportAllocateReq.getVerifyUserName());
        hiddenReport.setApproval(AuditStatusEnum.WAIT_VERIFY.getValue());
        //通过userId查询小程序用户id
        LambdaQueryWrapper<AppletUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(AppletUser::getPlatformUserId, hiddenReportAllocateReq.getVerifyUserId());
        AppletUser appletUser = appletUserMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(appletUser)){
            hiddenReport.setVerifyUserAppletId(appletUser.getUserId());
            //return BaseRespUtil.Error("10001","小程序用户不存在");
            log.error("当前分配人员未注册小程序！");

        }


        this.updateById(hiddenReport);
        return BaseRespUtil.Success();
    }

    @Override
    public BaseResp<List<HiddenReportResp>> queryList(HiddenReportListReq hiddenReportListReq) {
        //获取当前登录人
        LoginUser userInfo = AuthConstant.userLocal.get();

        //添加查询条件
        LambdaQueryWrapper<HiddenReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(hiddenReportListReq.getUserName()), HiddenReport::getUserName, hiddenReportListReq.getUserName());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(hiddenReportListReq.getUserPhone()), HiddenReport::getUserPhone, hiddenReportListReq.getUserPhone());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(hiddenReportListReq.getHiddenType()), HiddenReport::getHiddenType, hiddenReportListReq.getHiddenType());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(hiddenReportListReq.getHiddenLevel()), HiddenReport::getHiddenLevel, hiddenReportListReq.getHiddenLevel());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(hiddenReportListReq.getRectificationOrgId()), HiddenReport::getRectificationOrgId, hiddenReportListReq.getRectificationOrgId());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(hiddenReportListReq.getCurrentStatus()), HiddenReport::getCurrentStatus, hiddenReportListReq.getCurrentStatus());
        lambdaQueryWrapper.in(ObjectUtil.isNotEmpty(hiddenReportListReq.getApprovals()), HiddenReport::getApproval, hiddenReportListReq.getApprovals());
        //包含查询待核实状态，添加核实人id
        if (ObjectUtil.isNotEmpty(hiddenReportListReq.getApprovals())) {
            if (hiddenReportListReq.getApprovals().contains(AuditStatusEnum.WAIT_VERIFY.getValue())) {
                lambdaQueryWrapper.eq(HiddenReport::getVerifyUserId, userInfo.getPlatformUserId());
            }
            if (hiddenReportListReq.getApprovals().contains(AuditStatusEnum.BIZ_AUDIT.getValue())) {
                lambdaQueryWrapper.eq(HiddenReport::getRectificationUserId, userInfo.getPlatformUserId());
            }
            if (hiddenReportListReq.getApprovals().contains(AuditStatusEnum.BIZ_AUDIT.getValue())) {
                lambdaQueryWrapper.eq(HiddenReport::getRectificationUserId, userInfo.getPlatformUserId());
            }
            if (hiddenReportListReq.getApprovals().contains(AuditStatusEnum.CHARGE_AUDIT.getValue())) {
                lambdaQueryWrapper.eq(HiddenReport::getChargeLeaderId, userInfo.getPlatformUserId());
            }
            if (hiddenReportListReq.getApprovals().contains(AuditStatusEnum.MAIN_AUDIT.getValue())) {
                lambdaQueryWrapper.eq(HiddenReport::getMainLeaderId, userInfo.getPlatformUserId());
            }
        }


        lambdaQueryWrapper.orderByDesc(HiddenReport::getCreateTime);

        //分页查询
        List<HiddenReport> hiddenReportList = this.getBaseMapper().selectList(lambdaQueryWrapper);
        List<HiddenReportResp> hiddenReportRespList = hiddenReportList.stream().map(hiddenReport -> {
            HiddenReportResp hiddenReportResp = Convert.convert(HiddenReportResp.class, hiddenReport);
            //类型转换
            hiddenReportResp.setHiddenTypeStr(dictService.getChildeLableByValue("hiddenType", hiddenReport.getHiddenType().toString()));
            //风险等级 如果 hiddenReport.getHiddenLevel()为null则返回未知
            hiddenReportResp.setHiddenLevelStr(ObjectUtil.isNull(hiddenReport.getHiddenLevel()) ? "未知" : dictService.getChildeLableByValue("hiddenLevel", hiddenReport.getHiddenLevel().toString()));
            return hiddenReportResp;
        }).collect(Collectors.toList());
        return BaseRespUtil.Success(hiddenReportRespList);
    }

    @Override
    public BaseResp verifyHidden(HiddenReportVerifyReq hiddenReportVerifyReq) {
        HiddenReport hiddenReport = this.queryEntity(hiddenReportVerifyReq.getReportId());
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        if(ObjectUtil.notEqual(hiddenReport.getVerifyUserId(), saBaseLoginUser.getPlatformUserId())){
            throw new UABPException("task","您不是该隐患核实人！");
        }
        hiddenReport.setVerifyTime(DateUtil.date());
        hiddenReport.setVerifyResult(hiddenReportVerifyReq.getVerifyResult());
        hiddenReport.setVerifySituation(hiddenReportVerifyReq.getVerifySituation());
        hiddenReport.setHiddenAddr(hiddenReportVerifyReq.getHiddenAddr());
        //解析图片数量
        String paths = CollUtil.join(hiddenReportVerifyReq.getFliePathImage(), ";");
        hiddenReport.setVerifyImage(paths);

        if(hiddenReportVerifyReq.getVerifyResult()!=1){
            hiddenReport.setCurrentStatus(ShowStatusEnum.NOT_ADPOT.getValue());
            hiddenReport.setApproval(AuditStatusEnum.FINISHED.getValue());
        }else{
            hiddenReport.setCurrentStatus(ShowStatusEnum.ADPOT.getValue());
            hiddenReport.setApproval(AuditStatusEnum.MGR_AUDIT.getValue());
            hiddenReport.setSuggestionMeasures(hiddenReportVerifyReq.getSuggestionMeasures());
        }
        this.updateById(hiddenReport);
        return BaseRespUtil.Success();
    }

    @Override
    public BaseResp mgrAudit(HiddenReportMgrAuditReq hiddenReportMgrAuditReq) {
        //获取当前登录人
        LoginUser userInfo = AuthConstant.userLocal.get();

        HiddenReport hiddenReport = this.queryEntity(hiddenReportMgrAuditReq.getReportId());
        hiddenReport.setSuggestionRewards(hiddenReportMgrAuditReq.getSuggestionRewards());
        hiddenReport.setHiddenLevel(hiddenReportMgrAuditReq.getHiddenLevel());
        hiddenReport.setAuditRemark("");
        // 一般问题流程结束
        if(ObjectUtil.equal(HiddenLevelEnum.NORMAL.getValue(), hiddenReport.getHiddenLevel())){
            hiddenReport.setCurrentStatus(ShowStatusEnum.WAIT_REWARD.getValue());
            hiddenReport.setApproval(AuditStatusEnum.FINISHED.getValue());
            hiddenReport.setHiddenRewards(hiddenReportMgrAuditReq.getSuggestionRewards());
        }else {
            if(!ObjectUtil.equal(HiddenLevelEnum.NORMAL_HIDDEN.getValue(), hiddenReport.getHiddenLevel())) {
                //如果不是一般隐患，需要增加质安部长、分管领导、主要领导
                // 取质安部长
                UserListByRoleListReq userListByRoleListReq= new UserListByRoleListReq();
                userListByRoleListReq.setRoleCodeList(Arrays.asList("role_safety"));
                List<SysUser> userList = sysRoleService.getUserListByRoleCodeList(userListByRoleListReq);
                if(ObjectUtil.isEmpty(userList)){
                    throw new UABPException("task","未配置质安部部长！");
                }
                hiddenReport.setSafetyLeaderId(userList.get(0).getId());
                hiddenReport.setSafetyLeaderName(userList.get(0).getName());
                //取分管领导
                //通过userId查询小程序用户id
                LambdaQueryWrapper<AppletUser> queryWrapper = new LambdaQueryWrapper();
                queryWrapper.eq(AppletUser::getPlatformUserId, hiddenReportMgrAuditReq.getChargeLeaderId());
                AppletUser appletUser = appletUserMapper.selectOne(queryWrapper);
                if (ObjectUtil.isNotEmpty(appletUser)){
                    hiddenReport.setChargeLeaderId(appletUser.getUserId());
                    log.error("当前分配人员未注册小程序！");
                }
                hiddenReport.setChargeLeaderId(hiddenReportMgrAuditReq.getChargeLeaderId());
                hiddenReport.setChargeLeaderName(hiddenReportMgrAuditReq.getChargeLeaderName());

                //取主要领导
                //通过userId查询小程序用户id
                LambdaQueryWrapper<AppletUser> queryWrapperMain = new LambdaQueryWrapper();
                queryWrapperMain.eq(AppletUser::getPlatformUserId, hiddenReportMgrAuditReq.getMainLeaderId());
                AppletUser appletUserMain = appletUserMapper.selectOne(queryWrapperMain);
                if (ObjectUtil.isNotEmpty(appletUserMain)){
                    hiddenReport.setMainLeaderAppletId(appletUserMain.getUserId());
                    log.error("当前分配人员未注册小程序！");
                }
                hiddenReport.setMainLeaderId(hiddenReportMgrAuditReq.getMainLeaderId());
                hiddenReport.setMainLeaderName(hiddenReportMgrAuditReq.getMainLeaderName());
            }
            //一般隐患
            hiddenReport.setApproval(AuditStatusEnum.SUPERVISE_AUDIT.getValue());
            hiddenReport.setRectificationOrgId(hiddenReportMgrAuditReq.getRectificationOrgId());
            hiddenReport.setRectificationOrgName(hiddenReportMgrAuditReq.getRectificationOrgName());
            //获取部门主任
            // 业务部门主任信息
            List<SysUser> bizUserList = sysRoleMapper.listOrgRoleUser(hiddenReportMgrAuditReq.getRectificationOrgId(),"role_biz");
            if(ObjectUtil.isEmpty(bizUserList)){
                throw new UABPException("task","该部门未配置领导信息！");
            }
            //通过userId查询小程序用户id
            LambdaQueryWrapper<AppletUser> queryWrapperRectification = new LambdaQueryWrapper();
            queryWrapperRectification.eq(AppletUser::getPlatformUserId, bizUserList.get(0).getId());
            AppletUser appletUserRectification = appletUserMapper.selectOne(queryWrapperRectification);
            if (ObjectUtil.isNotEmpty(appletUserRectification)){
                hiddenReport.setRectificationUserAppletId(appletUserRectification.getUserId());
                log.error("当前分配人员未注册小程序！");
            }

            hiddenReport.setRectificationUserId(bizUserList.get(0).getId());
            hiddenReport.setRectificationUserName(bizUserList.get(0).getName());
            hiddenReport.setRectificationPeriod(hiddenReportMgrAuditReq.getRectificationPeriod());
            // 写入审核记录
            ReportAuditRecord reportAuditRecord = new ReportAuditRecord();
            reportAuditRecord.setReportId(hiddenReport.getReportId());
            reportAuditRecord.setRecordName(AuditFlowNameEnum.MGR_AUDIT.getDesc());
            reportAuditRecord.setCreateUserId(userInfo.getPlatformUserId());
            reportAuditRecord.setCreateTime(DateUtil.date());
            //获取平台用户
            SysUser sysUser = sysUserMapper.selectById(userInfo.getPlatformUserId());
            if (ObjectUtil.isNotEmpty(sysUser)) {
                reportAuditRecord.setCreateUserName(sysUser.getName());
            }
            reportAuditRecord.setCurrentStatus(AuditStatusEnum.MGR_AUDIT.getValue());
            reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
            // 取监督站站长
            UserListByRoleListReq userListByRoleListReq= new UserListByRoleListReq();
            userListByRoleListReq.setRoleCodeList(Arrays.asList("role_supervise"));
            List<SysUser> userList = sysRoleService.getUserListByRoleCodeList(userListByRoleListReq);
            if(ObjectUtil.isEmpty(userList)){
                throw new UABPException("task","未配置监督站站长！");
            }
            reportAuditRecord.setNextUserId(userList.get(0).getId());
            reportAuditRecord.setNextUserName(userList.get(0).getName());
            reportAuditRecord.setNextStatus(AuditStatusEnum.SUPERVISE_AUDIT.getValue());
            reportAuditRecord.setRemark("隐患定级");
            this.reportAuditRecordMapper.insert(reportAuditRecord);
        }
        this.baseMapper.updateById(hiddenReport);
        return BaseRespUtil.Success();
    }

    @Transactional
    @Override
    public BaseResp superviseAudit(HiddenReportSuperviseAuditReq hiddenReportSuperviseAuditReq) {
        //获取当前登录人
        LoginUser userInfo = AuthConstant.userLocal.get();

        HiddenReport hiddenReport = this.queryEntity(hiddenReportSuperviseAuditReq.getReportId());
        ReportAuditRecord reportAuditRecord = new ReportAuditRecord();
        reportAuditRecord.setReportId(hiddenReport.getReportId());
        reportAuditRecord.setRecordName(AuditFlowNameEnum.SUPERVISE_AUDIT.getDesc());
        reportAuditRecord.setCreateUserId(userInfo.getPlatformUserId());
        //获取平台用户
        SysUser sysUser = sysUserMapper.selectById(userInfo.getPlatformUserId());
        if (ObjectUtil.isNotEmpty(sysUser)) {
            reportAuditRecord.setCreateUserName(sysUser.getName());
        }
        reportAuditRecord.setCurrentStatus(AuditStatusEnum.SUPERVISE_AUDIT.getValue());
        if(ObjectUtil.notEqual(AuditResultEnum.PASS.getValue(), hiddenReportSuperviseAuditReq.getAuditResult())){
            hiddenReport.setApproval(AuditStatusEnum.MGR_AUDIT.getValue());
            hiddenReport.setHiddenRemark(hiddenReportSuperviseAuditReq.getAuditRemark());
            // 取审核管理员信息
            UserListByRoleListReq userListByRoleListReq= new UserListByRoleListReq();
            userListByRoleListReq.setRoleCodeList(Arrays.asList("role_audit"));
            List<SysUser> userList = sysRoleService.getUserListByRoleCodeList(userListByRoleListReq);
            if(ObjectUtil.isEmpty(userList)){
                throw new UABPException("task","未配置审核管理员！");
            }
            reportAuditRecord.setNextUserId(userList.get(0).getId());
            reportAuditRecord.setNextUserName(userList.get(0).getName());
            reportAuditRecord.setAuditStatus(AuditResultEnum.NOT_PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.MGR_AUDIT.getValue());
            reportAuditRecord.setRemark(hiddenReportSuperviseAuditReq.getAuditRemark());
        }else{
            hiddenReport.setApproval(AuditStatusEnum.BIZ_AUDIT.getValue());
            // 业务部门主任信息
            List<SysUser> bizUserList = sysRoleMapper.listOrgRoleUser(hiddenReport.getRectificationOrgId(),"role_biz");
            if(ObjectUtil.isEmpty(bizUserList)){
                throw new UABPException("task","该部门未配置领导信息！");
            }
            reportAuditRecord.setNextUserId(bizUserList.get(0).getId());
            reportAuditRecord.setNextUserName(bizUserList.get(0).getName());
            reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.BIZ_AUDIT.getValue());
        }
        reportAuditRecord.setRemark(hiddenReportSuperviseAuditReq.getAuditRemark());
        this.reportAuditRecordMapper.insert(reportAuditRecord);
        this.baseMapper.updateById(hiddenReport);
        return BaseRespUtil.Success();
    }

    @Override
    public BaseResp getReportRecord(ReportAuditRecordListReq reportAuditRecordListReq) {
        List<ReportAuditRecord> reportAuditRecordList = this.reportAuditRecordMapper.selectList(new QueryWrapper<ReportAuditRecord>().eq("report_id", reportAuditRecordListReq.getReportId()));
        //转换成ReportAuditRecordResp，使用类转换
        return BaseRespUtil.Success(reportAuditRecordList.stream().map(reportAuditRecord -> {
            ReportAuditRecordResp reportAuditRecordResp = new ReportAuditRecordResp();
            BeanUtils.copyProperties(reportAuditRecord, reportAuditRecordResp);
            return reportAuditRecordResp;
        }).collect(Collectors.toList()));

    }

    @Transactional
    @Override
    public BaseResp bizAudit(HiddenReportSuperviseAuditReq hiddenReportSuperviseAuditReq) {
        //获取当前登录人
        LoginUser userInfo = AuthConstant.userLocal.get();

        HiddenReport hiddenReport = this.queryEntity(hiddenReportSuperviseAuditReq.getReportId());
        ReportAuditRecord reportAuditRecord = new ReportAuditRecord();

        reportAuditRecord.setReportId(hiddenReport.getReportId());
        reportAuditRecord.setRecordName(AuditFlowNameEnum.BIZ_AUDIT.getDesc());
        reportAuditRecord.setCreateUserId(userInfo.getPlatformUserId());
        //获取平台用户
        SysUser sysUser = sysUserMapper.selectById(userInfo.getPlatformUserId());
        if (ObjectUtil.isNotEmpty(sysUser)) {
            reportAuditRecord.setCreateUserName(sysUser.getName());
        }
        reportAuditRecord.setCurrentStatus(AuditStatusEnum.BIZ_AUDIT.getValue());
        if(ObjectUtil.notEqual(AuditResultEnum.PASS.getValue(), hiddenReportSuperviseAuditReq.getAuditResult())){
            hiddenReport.setApproval(AuditStatusEnum.MGR_AUDIT.getValue());
            hiddenReport.setHiddenRemark(hiddenReportSuperviseAuditReq.getAuditRemark());

            // 取审核管理员信息
            UserListByRoleListReq userListByRoleListReq= new UserListByRoleListReq();
            userListByRoleListReq.setRoleCodeList(Arrays.asList("role_audit"));
            List<SysUser> userList = sysRoleService.getUserListByRoleCodeList(userListByRoleListReq);
            if(ObjectUtil.isEmpty(userList)){
                throw new UABPException("task","未配置审核管理员！");
            }
            reportAuditRecord.setNextUserId(userList.get(0).getId());
            reportAuditRecord.setNextUserName(userList.get(0).getName());

            reportAuditRecord.setAuditStatus(AuditResultEnum.NOT_PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.MGR_AUDIT.getValue());
            reportAuditRecord.setRemark(hiddenReportSuperviseAuditReq.getAuditRemark());
        }else{
            // 判断是否较大隐患和重大隐患，如果不是则流程结束，如果是则提交到质安环部长审核
            if(hiddenReport.getHiddenLevel()>HiddenLevelEnum.NORMAL_HIDDEN.getValue()){
                hiddenReport.setApproval(AuditStatusEnum.SAFETY_AUDIT.getValue());
                // 取质安环部长信息
                // 取审核管理员信息
                UserListByRoleListReq userListByRoleListReq= new UserListByRoleListReq();
                userListByRoleListReq.setRoleCodeList(Arrays.asList("role_safety"));
                List<SysUser> bizUserList = sysRoleService.getUserListByRoleCodeList(userListByRoleListReq);
                if(ObjectUtil.isEmpty(bizUserList)){
                    throw new UABPException("task","质安环部长未配置！");
                }

                reportAuditRecord.setNextUserId(bizUserList.get(0).getId());
                reportAuditRecord.setNextUserName(bizUserList.get(0).getName());
                reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
                reportAuditRecord.setNextStatus(AuditStatusEnum.SAFETY_AUDIT.getValue());
            }else{
                hiddenReport.setCurrentStatus(ShowStatusEnum.WAIT_REWARD.getValue());
                hiddenReport.setApproval(AuditStatusEnum.FINISHED.getValue());
                reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
                reportAuditRecord.setNextStatus(AuditStatusEnum.FINISHED.getValue());
            }
        }
        reportAuditRecord.setRemark(hiddenReportSuperviseAuditReq.getAuditRemark());
        this.reportAuditRecordMapper.insert(reportAuditRecord);
        this.baseMapper.updateById(hiddenReport);
        return BaseRespUtil.Success();
    }

    @Transactional
    @Override
    public BaseResp safetyAudit(HiddenReportSuperviseAuditReq hiddenReportSuperviseAuditReq) {
        //获取当前登录人
        LoginUser userInfo = AuthConstant.userLocal.get();
        HiddenReport hiddenReport = this.queryEntity(hiddenReportSuperviseAuditReq.getReportId());
        ReportAuditRecord reportAuditRecord = new ReportAuditRecord();
        reportAuditRecord.setReportId(hiddenReport.getReportId());
        reportAuditRecord.setRecordName(AuditFlowNameEnum.SUPERVISE_AUDIT.getDesc());

        reportAuditRecord.setCreateUserId(userInfo.getPlatformUserId());
        //获取平台用户
        SysUser sysUser = sysUserMapper.selectById(userInfo.getPlatformUserId());
        if (ObjectUtil.isNotEmpty(sysUser)) {
            reportAuditRecord.setCreateUserName(sysUser.getName());
        }
        reportAuditRecord.setCurrentStatus(AuditStatusEnum.SUPERVISE_AUDIT.getValue());
        if(ObjectUtil.notEqual(AuditResultEnum.PASS.getValue(), hiddenReportSuperviseAuditReq.getAuditResult())){
            hiddenReport.setApproval(AuditStatusEnum.MGR_AUDIT.getValue());
            hiddenReport.setHiddenRemark(hiddenReportSuperviseAuditReq.getAuditRemark());

            // 取审核管理员信息
            UserListByRoleListReq userListByRoleListReq= new UserListByRoleListReq();
            userListByRoleListReq.setRoleCodeList(Arrays.asList("role_audit"));
            List<SysUser> userList = sysRoleService.getUserListByRoleCodeList(userListByRoleListReq);
            if(ObjectUtil.isEmpty(userList)){
                throw new UABPException("task","未配置审核管理员！");
            }
            reportAuditRecord.setNextUserId(userList.get(0).getId());
            reportAuditRecord.setNextUserName(userList.get(0).getName());
            reportAuditRecord.setAuditStatus(AuditResultEnum.NOT_PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.MGR_AUDIT.getValue());
        }else{
            hiddenReport.setApproval(AuditStatusEnum.CHARGE_AUDIT.getValue());
            hiddenReport.setChargeLeaderId(hiddenReport.getChargeLeaderId());
            hiddenReport.setChargeLeaderName(hiddenReport.getChargeLeaderName());
            reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.CHARGE_AUDIT.getValue());
            reportAuditRecord.setNextUserId(hiddenReport.getChargeLeaderId());
            reportAuditRecord.setNextUserName(hiddenReport.getChargeLeaderName());
        }
        reportAuditRecord.setRemark(hiddenReportSuperviseAuditReq.getAuditRemark());
        this.reportAuditRecordMapper.insert(reportAuditRecord);
        this.baseMapper.updateById(hiddenReport);
        return BaseRespUtil.Success();
    }

    @Transactional
    @Override
    public BaseResp chargeAudit(HiddenReportSuperviseAuditReq hiddenReportSuperviseAuditReq) {
        //获取当前登录人
        LoginUser userInfo = AuthConstant.userLocal.get();
        HiddenReport hiddenReport = this.queryEntity(hiddenReportSuperviseAuditReq.getReportId());
        ReportAuditRecord reportAuditRecord = new ReportAuditRecord();
        reportAuditRecord.setReportId(hiddenReport.getReportId());
        reportAuditRecord.setRecordName(AuditFlowNameEnum.CHARGE_AUDIT.getDesc());


        reportAuditRecord.setCreateUserId(userInfo.getPlatformUserId());
        //获取平台用户
        SysUser sysUser = sysUserMapper.selectById(userInfo.getPlatformUserId());
        if (ObjectUtil.isNotEmpty(sysUser)) {
            reportAuditRecord.setCreateUserName(sysUser.getName());
        }

        reportAuditRecord.setCurrentStatus(AuditStatusEnum.CHARGE_AUDIT.getValue());
        if(ObjectUtil.notEqual(AuditResultEnum.PASS.getValue(), hiddenReportSuperviseAuditReq.getAuditResult())){
            hiddenReport.setApproval(AuditStatusEnum.MGR_AUDIT.getValue());
            hiddenReport.setHiddenRemark(hiddenReportSuperviseAuditReq.getAuditRemark());
            // 取审核管理员信息
            UserListByRoleListReq userListByRoleListReq= new UserListByRoleListReq();
            userListByRoleListReq.setRoleCodeList(Arrays.asList("role_audit"));
            List<SysUser> userList = sysRoleService.getUserListByRoleCodeList(userListByRoleListReq);
            if(ObjectUtil.isEmpty(userList)){
                throw new UABPException("task","未配置审核管理员！");
            }
            reportAuditRecord.setNextUserId(userList.get(0).getId());
            reportAuditRecord.setNextUserName(userList.get(0).getName());
            reportAuditRecord.setAuditStatus(AuditResultEnum.NOT_PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.MGR_AUDIT.getValue());

        }else{
            hiddenReport.setApproval(AuditStatusEnum.MAIN_AUDIT.getValue());
            hiddenReport.setMainLeaderId(hiddenReport.getMainLeaderId());
            hiddenReport.setMainLeaderName(hiddenReport.getMainLeaderName());
            reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.MAIN_AUDIT.getValue());
            reportAuditRecord.setNextUserId(hiddenReport.getMainLeaderId());
            reportAuditRecord.setNextUserName(hiddenReport.getMainLeaderName());
        }
        reportAuditRecord.setRemark(hiddenReportSuperviseAuditReq.getAuditRemark());
        this.reportAuditRecordMapper.insert(reportAuditRecord);
        this.baseMapper.updateById(hiddenReport);
        return BaseRespUtil.Success();
    }

    @Transactional
    @Override
    public BaseResp mainAudit(HiddenReportSuperviseAuditReq hiddenReportSuperviseAuditReq) {
        //获取当前登录人
        LoginUser userInfo = AuthConstant.userLocal.get();
        HiddenReport hiddenReport = this.queryEntity(hiddenReportSuperviseAuditReq.getReportId());
        ReportAuditRecord reportAuditRecord = new ReportAuditRecord();
        reportAuditRecord.setReportId(hiddenReport.getReportId());
        reportAuditRecord.setRecordName(AuditFlowNameEnum.MAIN_AUDIT.getDesc());

        reportAuditRecord.setCreateUserId(userInfo.getPlatformUserId());
        //获取平台用户
        SysUser sysUser = sysUserMapper.selectById(userInfo.getPlatformUserId());
        if (ObjectUtil.isNotEmpty(sysUser)) {
            reportAuditRecord.setCreateUserName(sysUser.getName());
        }

        reportAuditRecord.setCurrentStatus(AuditStatusEnum.MAIN_AUDIT.getValue());
        if(ObjectUtil.notEqual(AuditResultEnum.PASS.getValue(), hiddenReportSuperviseAuditReq.getAuditResult())){
            hiddenReport.setApproval(AuditStatusEnum.MGR_AUDIT.getValue());
            hiddenReport.setHiddenRemark(hiddenReportSuperviseAuditReq.getAuditRemark());
            // 取审核管理员信息
            UserListByRoleListReq userListByRoleListReq= new UserListByRoleListReq();
            userListByRoleListReq.setRoleCodeList(Arrays.asList("role_audit"));
            List<SysUser> userList = sysRoleService.getUserListByRoleCodeList(userListByRoleListReq);
            if(ObjectUtil.isEmpty(userList)){
                throw new UABPException("task","未配置审核管理员！");
            }
            reportAuditRecord.setNextUserId(userList.get(0).getId());
            reportAuditRecord.setNextUserName(userList.get(0).getName());
            reportAuditRecord.setAuditStatus(AuditResultEnum.NOT_PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.MGR_AUDIT.getValue());

        }else{
            hiddenReport.setCurrentStatus(ShowStatusEnum.WAIT_REWARD.getValue());
            hiddenReport.setApproval(AuditStatusEnum.FINISHED.getValue());
            reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.FINISHED.getValue());
        }
        reportAuditRecord.setRemark(hiddenReportSuperviseAuditReq.getAuditRemark());
        this.reportAuditRecordMapper.insert(reportAuditRecord);
        this.baseMapper.updateById(hiddenReport);
        return BaseRespUtil.Success();
    }

    @Override
    public BaseResp<List<HiddenReportResp>> queryListToTask() {

        //添加查询条件
        LambdaQueryWrapper<HiddenReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //审批完成的任务
        lambdaQueryWrapper.eq(HiddenReport::getApproval, AuditStatusEnum.FINISHED.getValue());
        //只有较大隐患和重大隐患才显示
        lambdaQueryWrapper.in(HiddenReport::getHiddenLevel, HiddenLevelEnum.LARGER_HIDDEN.getValue(), HiddenLevelEnum.MAJOR_HIDDEN.getValue());
        lambdaQueryWrapper.orderByDesc(HiddenReport::getCreateTime);

        //分页查询
        List<HiddenReport> hiddenReportList = this.getBaseMapper().selectList(lambdaQueryWrapper);
        List<HiddenReportResp> hiddenReportRespList = hiddenReportList.stream().filter(hiddenReport -> {
            //查询任务表是否当前隐患是否在任务表中
            return !taskMapper.isExistTask(hiddenReport.getReportId());
        }).map(hiddenReport -> {
            HiddenReportResp hiddenReportResp = Convert.convert(HiddenReportResp.class, hiddenReport);
            //类型转换
            hiddenReportResp.setHiddenTypeStr(dictService.getChildeLableByValue("hiddenType", hiddenReport.getHiddenType().toString()));
            //风险等级 如果 hiddenReport.getHiddenLevel()为null则返回未知
            hiddenReportResp.setHiddenLevelStr(ObjectUtil.isNull(hiddenReport.getHiddenLevel()) ? "未知" : dictService.getChildeLableByValue("hiddenLevel", hiddenReport.getHiddenLevel().toString()));
            return hiddenReportResp;
        }).collect(Collectors.toList());
        return BaseRespUtil.Success(hiddenReportRespList);
    }

    @Override
    public BaseResp<List<HiddenReportResp>> myReportList(HiddenReportListReq hiddenReportListReq) {
        //获取当前登录人
        LoginUser userInfo = AuthConstant.userLocal.get();

        //添加查询条件
        LambdaQueryWrapper<HiddenReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(HiddenReport::getUserId, userInfo.getUserId());
        lambdaQueryWrapper.orderByDesc(HiddenReport::getCreateTime);

        //分页查询
        List<HiddenReport> hiddenReportList = this.getBaseMapper().selectList(lambdaQueryWrapper);
        List<HiddenReportResp> hiddenReportRespList = hiddenReportList.stream().map(hiddenReport -> {
            HiddenReportResp hiddenReportResp = Convert.convert(HiddenReportResp.class, hiddenReport);
            //类型转换
            hiddenReportResp.setHiddenTypeStr(dictService.getChildeLableByValue("hiddenType", hiddenReport.getHiddenType().toString()));
            //风险等级 如果 hiddenReport.getHiddenLevel()为null则返回未知
            hiddenReportResp.setHiddenLevelStr(ObjectUtil.isNull(hiddenReport.getHiddenLevel()) ? "未知" : dictService.getChildeLableByValue("hiddenLevel", hiddenReport.getHiddenLevel().toString()));
            //获取隐患状态
            hiddenReportResp.setCurrentStatusStr(ShowStatusEnum.getNameByValue(hiddenReport.getCurrentStatus()));
            return hiddenReportResp;
        }).collect(Collectors.toList());
        return BaseRespUtil.Success(hiddenReportRespList);
    }


    public HiddenReport queryEntity(String id) {
        HiddenReport hiddenReport = this.getById(id);
        if(ObjectUtil.isEmpty(hiddenReport)) {
            throw new UABPException("task","隐患上报信息不存在！");
        }
        return hiddenReport;
    }

}
